<template>
  <div class="my">
    <van-nav-bar class="top-bar" title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号码"
        placeholder="请输入手机号码"
        required
        :rules="[
          { required: true, message: '请输入手机号码' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确手机号码'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="[
          { required: true, message: '请输入验证码' },
          { pattern: /\d{6}/, message: '请正确的验证码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="加载中..."
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script scoped>
// 导入 api方法
import { userLogin } from '../../api/login.js'
import { saveToken } from '../../utils/token'
export default {
  // 方便调试 建议写上和组件名相同

  name: 'login',
  create () {
    // console.log('userLogin:', userLogin)
  },
  data () {
    return {
      // 手机号
      mobile: '18888886666',
      // 验证码
      code: '246810',
      // 是否loading
      isLoading: false
    }
  },
  methods: {
    // 表单校验通过后出发回调函数
    onSubmit (values) {
      // console.log('submit', values)
      // 利用loading和禁用
      this.isLoading = true
      this.isDisabled = true
      userLogin(values)
        .then(res => {
          // console.log('res:', res)
          this.$toast.success('登录成功')
          // 关闭loading和禁用
          this.isLoading = false
          // this.isDisabled = false
          saveToken(res.data.data)
          // g根据url中的地址,决定跳转的路径
          if (this.$route.query.back) {
            this.$router.push({ path: this.$route.query.back })
          } else {
            // back没有值
            this.$router.push({ path: '/home' })
          }
        })
        .catch(errRes => {
          // console.log('errRes:', errRes)
          this.$toast.fail('验证码有误')
          // 关闭loading和禁用
          this.isLoading = false
          this.isDisabled = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
.my {
  .top-bar {
    background-color: rgb(49, 159, 231);
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
